﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using GP.Logic;
using GP.Logic.Model;

namespace Mvc.Controllers
{
    [Authorize]
    public partial class DoctorController : Controller
    {
        private readonly DoctorService _doctorService = new DoctorService();

        public virtual ActionResult Index()
        {
            List<Doctor> doctors = _doctorService.GetDoctors();
            return View(doctors);
        }

        // GET: /Doctor/Create

        public virtual ActionResult Create()
        {
            var newDoctor = _doctorService.CreateNewDoctor();
            return RedirectToAction(MVC.Doctor.Edit(newDoctor.DocId));
        } 

        //
        // POST: /Doctor/Create

        public virtual ActionResult Edit(long id)
        {
            var doctor = _doctorService.GetDoctor(id);
            return View(Views.Edit, doctor);
        }

        public virtual ActionResult EditUser(long userId)
        {
            var user = _doctorService.GetUser(userId);
            return View(Views.EditUser, user);
        }

        public virtual ActionResult DeleteUser(long userId)
        {
            var user = _doctorService.GetUser(userId);
            _doctorService.DeleteUser(userId);
            return RedirectToAction(Actions.Edit(user.DocId));
        }

        [HttpPost]
        public virtual ActionResult EditUser(long userId, GpSysUser user)
        {
            try
            {
                GpSysUser oldUser = _doctorService.SaveUser(userId, user);
                return RedirectToAction(MVC.Doctor.Edit(oldUser.DocId));
            }
            catch
            {
                return View(Views.EditUser, user);
            }
        }

        public virtual ActionResult CreateUser(long docId)
        {
            var user = _doctorService.CreateNewUser(docId);
            return RedirectToAction(MVC.Doctor.EditUser(user.UserId));
        }

        [HttpPost]
        public virtual ActionResult Edit(long docId, Doctor doctor)
        {
            try
            {
                _doctorService.SaveDoctor(docId, doctor);
                return RedirectToAction(MVC.Doctor.Index());
            }
            catch
            {
                return View(Views.Edit, doctor);
            }
        }

        //
        // GET: /Doctor/Delete/5

        public virtual ActionResult Delete(long id)
        {
            _doctorService.DeleteDoctor(id);
            return RedirectToAction(Actions.Index());
        }
    }
}
